package com.beiding.listener;

import com.beiding.dao.OrderDao;
import com.beiding.pojo.order.Order;
import com.beiding.service.impl.MessageSender;
import com.beiding.timeout.bean.TimeShaft;
import com.beiding.utils.LogUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CheckIn extends TimeoutListener {

    protected CheckIn(OrderDao orderDao, TimeShaft<String> timeShaft) {
        super(orderDao, timeShaft, "checkIn");
    }


    private MessageSender sender;

    @Autowired
    public void setSender(MessageSender sender) {
        this.sender = sender;
    }
    @Override
    public void run(String id) {
        Order order = orderDao.getInsensitive(id);

        if (judge(order, Order.ACCEPTED, Order.REFUND_DISPUTE)) {

            order.setUseTimestamp(System.currentTimeMillis());

            Document document = new Document();

            document.put("state", Order.USING);

            document.put("useTimestamp", order.getUseTimestamp());

            document.put("expireTimestamp", order.getExpireTimestamp());

            document.put("usingMilliseconds", order.getUsingMilliseconds());

            orderDao.updateFields(id, document);

            order.setState(Order.USING);

            //更新订单未受理状态
            sender.sendToTenant(order.getHolderId(), update(order));
            sender.sendToLandlord(order.getLandlord(), update(order));

            timeShaft.delay("expire", order.getUsingMilliseconds(), id);

        }
    }
}

